<template>
  <div class="teacher-attendance-view">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ $t('attendance.records') }}</span>
      </div>
      
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item :label="$t('course.title')">
          <el-select v-model="queryForm.courseId" :placeholder="$t('common.pleaseSelect') + ' ' + $t('course.title')" clearable>
            <el-option
              v-for="course in teacherCourses"
              :key="course.id"
              :label="course.name"
              :value="course.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item :label="$t('group.title')">
          <el-select v-model="queryForm.groupId" :placeholder="$t('common.pleaseSelect') + ' ' + $t('group.title')" clearable>
            <el-option
              v-for="group in teacherGroups"
              :key="group.id"
              :label="group.name"
              :value="group.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('attendance.status')">
          <el-select v-model="queryForm.status" :placeholder="$t('common.pleaseSelect') + ' ' + $t('attendance.status')" clearable>
            <el-option :label="$t('attendance.normal')" :value="0"></el-option>
            <el-option :label="$t('attendance.late')" :value="1"></el-option>
            <el-option :label="$t('attendance.earlyLeave')" :value="2"></el-option>
            <el-option :label="$t('attendance.absent')" :value="3"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item :label="$t('attendance.dateRange')">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            :range-separator="$t('common.to')"
            :start-placeholder="$t('attendance.startDate')"
            :end-placeholder="$t('attendance.endDate')"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleQuery">{{ $t('common.search') }}</el-button>
          <el-button @click="resetQuery">{{ $t('common.reset') }}</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="attendanceRecords" style="width: 100%">
        <el-table-column prop="userId" :label="$t('user.id')"></el-table-column>
        <el-table-column :label="$t('attendance.studentName')">
          <template slot-scope="scope">
            {{ getStudentName(scope.row.userId) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('attendance.courseName')">
          <template slot-scope="scope">
            {{ getCourseName(scope.row.courseId) }}
          </template>
        </el-table-column>
        <el-table-column prop="checkInTime" :label="$t('attendance.checkTime')"></el-table-column>
        <el-table-column :label="$t('attendance.status')">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" :label="$t('common.remark')"></el-table-column>
        <el-table-column :label="$t('common.operation')" width="150" v-if="!isMobile">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="viewDetail(scope.row)">{{ $t('common.detail') }}</el-button>
            <el-button type="text" size="small" @click="editRecord(scope.row)">{{ $t('common.edit') }}</el-button>
          </template>
        </el-table-column>
        <!-- 移动端操作列 -->
        <el-table-column :label="$t('common.operation')" width="95" fixed="right" v-if="isMobile">
          <template slot-scope="scope">
            <el-popover
              placement="left"
              width="120"
              trigger="click">
              <div class="mobile-operation-buttons">
                <el-button type="text" size="small" @click="viewDetail(scope.row)">{{ $t('common.detail') }}</el-button>
                <el-button type="text" size="small" @click="editRecord(scope.row)">{{ $t('common.edit') }}</el-button>
              </div>
              <el-button slot="reference" type="primary" size="mini">
                {{ $t('common.operation') }} <i class="el-icon-arrow-down"></i>
              </el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryForm.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryForm.size"
          :layout="paginationLayout"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 考勤详情对话框 -->
    <el-dialog :title="$t('attendance.recordDetail')" :visible.sync="detailDialogVisible" width="500px">
      <el-descriptions :column="1" border>
        <el-descriptions-item :label="$t('attendance.studentName')">{{ currentRecord.studentName }}</el-descriptions-item>
        <el-descriptions-item :label="$t('attendance.courseName')">{{ currentRecord.courseName }}</el-descriptions-item>
        <el-descriptions-item :label="$t('attendance.checkTime')">{{ currentRecord.checkInTime }}</el-descriptions-item>
        <el-descriptions-item :label="$t('attendance.status')">{{ getStatusText(currentRecord.status) }}</el-descriptions-item>
        <el-descriptions-item :label="$t('attendance.checkLocation')">
          {{ $t('attendance.longitude') }}: {{ currentRecord.locationLongitude }}, {{ $t('attendance.latitude') }}: {{ currentRecord.locationLatitude }}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('common.remark')">{{ currentRecord.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 修改考勤记录对话框 -->
    <el-dialog :title="$t('attendance.editRecord')" :visible.sync="editDialogVisible" width="500px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item :label="$t('attendance.status')">
          <el-select v-model="editForm.status" :placeholder="$t('common.pleaseSelect') + ' ' + $t('attendance.status')">
            <el-option :label="$t('attendance.normal')" :value="0"></el-option>
            <el-option :label="$t('attendance.late')" :value="1"></el-option>
            <el-option :label="$t('attendance.earlyLeave')" :value="2"></el-option>
            <el-option :label="$t('attendance.absent')" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.remark')">
          <el-input type="textarea" v-model="editForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="submitEdit">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import request from '@/utils/request'

export default {
  name: 'TeacherAttendanceView',
  data() {
    return {
      queryForm: {
        courseId: null,
        groupId: null,
        status: null,
        startDate: null,
        endDate: null,
        current: 1,
        size: 10
      },
      dateRange: [],
      teacherCourses: [],
      teacherGroups: [],
      attendanceRecords: [],
      total: 0,
      detailDialogVisible: false,
      editDialogVisible: false,
      currentRecord: {},
      editForm: {
        status: null,
        remark: ''
      },
      studentMap: new Map(),
      courseMap: new Map(),
      isMobile: false,
      screenWidth: document.body.clientWidth,
      paginationLayout: "total, sizes, prev, pager, next, jumper"
    }
  },
  computed: {
    userId() {
      return getUserId()
    }
  },
  watch: {
    dateRange(val) {
      if (val) {
        this.queryForm.startDate = val[0]
        this.queryForm.endDate = val[1]
      } else {
        this.queryForm.startDate = null
        this.queryForm.endDate = null
      }
    }
  },
  created() {
    this.getTeacherCourses()
    this.getTeacherGroups()
    this.getAttendanceRecords()
    this.checkScreenSize()
  },
  mounted() {
    window.addEventListener('resize', this.handleResize)
    this.checkScreenSize()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    handleResize() {
      this.screenWidth = document.body.clientWidth
      this.checkScreenSize()
    },
    checkScreenSize() {
      this.isMobile = this.screenWidth < 768
      
      // 根据屏幕尺寸调整分页控件布局
      if (this.isMobile) {
        this.paginationLayout = "prev, pager, next"
      } else {
        this.paginationLayout = "total, sizes, prev, pager, next, jumper"
      }
    },
    async getTeacherCourses() {
      try {
        const res = await request.get(`/course/teacher/${this.userId}`)
        
        if (res.code === 200) {
          this.teacherCourses = res.data || []
          this.courseMap = new Map(this.teacherCourses.map(course => [course.id, course.name]))
        } else {
          this.$message.error(res.msg || '获取课程列表失败')
        }
      } catch (error) {
        console.error('获取课程列表失败:', error)
        this.$message.error('获取课程列表失败')
      }
    },
    async getTeacherGroups() {
      try {
        const res = await request.get(`/group/teacher-groups/${this.userId}`)
        
        if (res.code === 200) {
          this.teacherGroups = res.data || []
        } else {
          this.$message.error(res.msg || '获取班级列表失败')
        }
      } catch (error) {
        console.error('获取班级列表失败:', error)
        this.$message.error('获取班级列表失败')
      }
    },
    async getAttendanceRecords() {
      try {
        const res = await request.get('/attendance/page', {
          params: this.queryForm
        })
        
        if (res.code === 200) {
          this.attendanceRecords = res.data.records || []
          this.total = res.data.total || 0
          
          // 获取学生信息
          const studentIds = [...new Set(this.attendanceRecords.map(record => record.userId))]
          await this.getStudentsInfo(studentIds)
        } else {
          this.$message.error(res.msg || '获取考勤记录失败')
        }
      } catch (error) {
        console.error('获取考勤记录失败:', error)
        this.$message.error('获取考勤记录失败')
      }
    },
    async getStudentsInfo(studentIds) {
      try {
        for (const id of studentIds) {
          if (!this.studentMap.has(id)) {
            const res = await request.get(`/user/${id}`)
            if (res.code === 200 && res.data) {
              this.studentMap.set(id, res.data.name || `用户${id}`)
            } else {
              this.studentMap.set(id, `用户${id}`)
              console.warn(`获取用户 ${id} 信息失败: ${res.msg || '未知错误'}`)
            }
          }
        }
      } catch (error) {
        console.error('获取学生信息失败:', error)
      }
    },
    getStudentName(userId) {
      return this.studentMap.get(userId) || userId
    },
    getCourseName(courseId) {
      return this.courseMap.get(courseId) || courseId
    },
    getStatusText(status) {
      const statusMap = {
        0: '正常',
        1: '迟到',
        2: '早退',
        3: '旷课'
      }
      return statusMap[status] || '未知'
    },
    getStatusType(status) {
      const typeMap = {
        0: 'success',
        1: 'warning',
        2: 'warning',
        3: 'danger'
      }
      return typeMap[status] || 'info'
    },
    handleQuery() {
      this.queryForm.current = 1
      this.getAttendanceRecords()
    },
    resetQuery() {
      this.queryForm = {
        courseId: null,
        groupId: null,
        status: null,
        startDate: null,
        endDate: null,
        current: 1,
        size: 10
      }
      this.dateRange = []
      this.getAttendanceRecords()
    },
    handleSizeChange(val) {
      this.queryForm.size = val
      this.getAttendanceRecords()
    },
    handleCurrentChange(val) {
      this.queryForm.current = val
      this.getAttendanceRecords()
    },
    viewDetail(row) {
      this.currentRecord = {
        ...row,
        studentName: this.getStudentName(row.userId),
        courseName: this.getCourseName(row.courseId)
      }
      this.detailDialogVisible = true
    },
    editRecord(row) {
      this.currentRecord = row
      this.editForm = {
        status: row.status,
        remark: row.remark
      }
      this.editDialogVisible = true
    },
    async submitEdit() {
      try {
        const requestData = {
          courseId: this.currentRecord.courseId,
          userId: this.currentRecord.userId,
          status: this.editForm.status,
          remark: this.editForm.remark,
          locationLatitude: this.currentRecord.locationLatitude, 
          locationLongitude: this.currentRecord.locationLongitude
        }
        
        const res = await request.put(`/attendance/update/${this.currentRecord.id}`, requestData)
        
        if (res.code === 200) {
          this.$message.success('修改成功')
          this.editDialogVisible = false
          this.getAttendanceRecords()
        } else {
          this.$message.error(res.msg || '修改失败')
        }
      } catch (error) {
        console.error('修改考勤记录失败:', error)
        this.$message.error('修改失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.teacher-attendance-view {
  padding: 20px;
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
  
  .mobile-operation-buttons {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }

  .mobile-operation-buttons .el-button {
    margin-left: 0;
    margin-bottom: 8px;
    width: 100%;
    text-align: left;
  }

  .mobile-operation-buttons .el-button:last-child {
    margin-bottom: 0;
  }
}

@media screen and (max-width: 768px) {
  .demo-form-inline .el-form-item {
    display: block;
    margin-right: 0;
    margin-bottom: 10px;
    width: 100%;
  }

  .demo-form-inline .el-select,
  .demo-form-inline .el-date-editor {
    width: 100%;
  }

  .el-table {
    width: 100%;
    font-size: 12px;
  }
  
  .el-button {
    padding: 7px 10px;
    font-size: 12px;
  }
}
</style> 